import 'dart:async';

import 'package:flutter_base/common/fun.dart';
import 'package:flutter_base/widgets/refreshListView.dart';

/// Create： Zhang 4/2/21 8:58 AM
/// 描述：数据处理类的基类
class PageModel {
  ///页面是否被销毁
  bool _isDisPose = false;

  ///页面的状态,默认为加载状态
  LoadingState loadingState = LoadingState.LOADING;

  ///流控制器
  StreamController? _controller;

  ///流订阅
  StreamSubscription? _subscription;

  ///回调方法
  Notify? _notifyChange;

  void init() {
    _isDisPose = false;
  }

  ///监听流时间,更新UI
  ///注意:目前只实现了单数据流订阅,请保持一个pageModel只对应一个page
  void update(Notify notify) {
    _notifyChange = notify;
  }

  ///通知变更
  void notify() {
    if (_isDisPose) {
      return;
    }
    //避免重复创建流，请严格保证一个pageModel对应一个page
    if (_controller == null && _subscription == null) {
      _controller = StreamController();

      _subscription = _controller!.stream.listen((event) {
        if (_notifyChange != null) {
          _notifyChange!();
        }
      });
    }

    _controller?.add(DateTime.now().millisecondsSinceEpoch);
  }

  ///页面销毁的回调
  void onDispose() {
    _isDisPose = true;
    if (_subscription != null) {
      _subscription?.cancel();
      _subscription = null;
    }
    if (_controller != null) {
      _controller?.close();
      _controller = null;
    }
  }
}
